package fr.uvsq.isty.bdh.hchess.gui.game;

import fr.uvsq.isty.bdh.hchess.engine.GameData;
import fr.uvsq.isty.bdh.hchess.gui.style.Style;
import fr.uvsq.isty.bdh.hchess.interfacing.GameEndResult;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;

/**
 * Display who is the current player (black or white) or if the game is over who is 
 * the winner (black, white or draw).
 * @author Rémi Dubois <RemiEric.Dubois@gmail.com>
 */
public class CurrentPlayerDisplay extends JPanel implements Observer {
    
    private boolean blackPlayerTurn;
    
    private boolean gameOver;
    private GameEndResult result;
    
    private Style style; /** Board style singleton */

    public CurrentPlayerDisplay() {
        this.setPreferredSize(new Dimension(
                (BoardDisplay.DEFAULT_CASE_WIDTH/2),
                (BoardDisplay.DEFAULT_CASE_HEIGHT*1)));
        
        try {
            this.style = Style.getInstance();
        } catch (IOException ex) {
        }
        
        gameOver = false;
    }
    
    @Override
    public void paintComponent(Graphics g) {
        Image img;
        g.setColor(Color.GRAY);
        
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        
        if(!gameOver) {
            img = style.getPlayerTurnImage(blackPlayerTurn);
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        }
        else {
            if (result == GameEndResult.BLACK_WIN) {
                img = style.getEndImage("blackWin");
            }
            else if (result == GameEndResult.WHITE_WIN) {
                img = style.getEndImage("whiteWin");
            }
            else {
                img = style.getEndImage("draw");
            }
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    }
    
    public void update(Observable o, Object arg) {
        if(o instanceof GameData) {
            GameData gameData = (GameData) o;
            
            blackPlayerTurn = gameData.isBlackTurnToPlay();
            gameOver = gameData.isGameOver();
            
            if(gameOver) {
                result = gameData.getResult();
            }
            
            this.repaint();
        }
    }
    
}
